package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.StrategyFactory;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

@Component("1002")
@Slf4j
public class TrackStrategy implements StrategyFactory {

    @Autowired
    private UserPaidTrackService userPaidTrackService;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("处理购买项目类型为：声音");

        // 重复提交调用,导致重复保存,所以先利用订单号(唯一性)查询数据库
        LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPaidTrack::getOrderNo,userPaidRecordVo.getOrderNo());
        long count = userPaidTrackService.count(wrapper);
        if(count > 0) return;

        TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
        Long albumId = trackInfo.getAlbumId();


        List<UserPaidTrack> userPaidTrackList = new ArrayList<>();
        userPaidRecordVo.getItemIdList().forEach(new Consumer<Long>() {
            @Override
            public void accept(Long trackId) {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                userPaidTrack.setTrackId(trackId);
                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                userPaidTrack.setAlbumId(albumId);
                userPaidTrackList.add(userPaidTrack);
            }
        });
        userPaidTrackService.saveBatch(userPaidTrackList);
    }
}
